<!--
  datatable 数据表格宏
      参数定义：
  	  target:ajax 数据的url
  	  title:表格标题  如['name','age'] 
  	  rows: 表格列数据  如['name','age'] 
  	  formatter：表格列格式化 具体请看datatable columnDefs
  	  keyId:数据主键
  	  batch:批量操作 默认为false 为true 会在第一列加上checkbox
  	  batchId:批量操作的id数组属性名
  datatable 配置参考：http://dt.thxopen.com/reference/option/
  -->
<#macro datatable paging=true  target="action" titles=[] rows=[]  formatter=[] keyId="id" 
		batch=false batchId="ids" operations=[]  formid="queryForm" reset=true,search=true
		title="管理列表" batchAction=[] title_icon="user" drawEvent="" >
<div class="portlet">
	<div class="portlet-title">
		<div class="caption">
			<i class="fa fa-${title_icon}"></i>${title!}
		</div>
		<div class="actions">
		<#if batchAction??&&batchAction?size gt 0>
			<#list batchAction as action>
				<a href="javascript:;" onclick="<#if action.js??>${action.js}(b_${action.tag})<#else>_batchop(b_${action.tag})</#if>" class="btn btn-default"><i class="fa fa-${action.icon!}"></i> ${action.label}</a>
			</#list>
		</#if>
			<#if reset><a href="javascript:;" class="btn btn-default btn reset"><i class="icon-reload"></i> 重置  </a></#if>
			<#if search><a href="javascript:;" onclick="reload()" class="btn btn-default btn refresh"><i class="fa fa-search"></i> 搜索  </a></#if>
		</div>
	</div>
	<!--keyid隐藏域  -->
	<input type="hidden" name="${keyId}" id="${keyId}"></input>
	<#nested>
	<div class="portlet-body">
		<table class="table table-striped table-bordered table-hover"
			id="sample_dt" width="100%">
			<thead>
				<tr>
				<#if batch>
					<th class="table-checkbox">
						<input type="checkbox" id="checkbox-all" class="group-checkable regular-checkbox"  data-set="#sample_dt .regular-checkbox"/><label for="checkbox-all"></label>
					</th>
				</#if>
				<#if titles??&&titles?size gt 0>	
					<#list titles as title>
						<th>${title!}</th>
					</#list>
				</#if>
				<#if operations??&&operations?size gt 0>	
					<th>操作</th>
				</#if>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	</div>
</div>
<script>
	var table  = $('#sample_dt');
	var dt;
	$(function(){
		doinit();
	})
	function doinit(){
		if (!jQuery().dataTable) {
            return;
        }
		dt = table.dataTable({
			"paging":${paging?c},
	    	"processing": true,//是否显示处理状态(排序的时候，数据很多耗费时间长的话，也会显示这个)
			"stateSave": true,//保存状态 - 在页面重新加载的时候恢复状态（页码等内容）
			"searching": false,//是否允许Datatables开启本地搜索
			"ordering" : false,//是否允许Datatables开启排序
			"dom" : 'rt<"#bottom"<#if paging>ilp</#if><"clear">>',//定义DataTables的组件元素的显示和显示顺序
			"pagingType": "full_numbers",//分页类型
			"serverSide" : true,//是否开启服务器模式
			"ajax":{
				"url":"${target}",
				"type":"post",
				"data":function(d){
					
					var data={}; 
					data.draw = d.draw;
					data.start = d.start;
					data.length = d.length;
		            $($("#${formid!}").serializeArray()).each(function(){  
		                data[this.name]=this.value;  
		            }); 
					return data;
					//return putQueryData("#${formid!}",d);
				}
			},
			//"sAjaxSource" : "${target}",//1.9版本ajax 数据地址使用该配置比v1.10 ajax{} 配置好v1.10 ajax会传很多参数到后台
			//"sServerMethod" : "POST",//ajax method
			// "fnServerParams": function ( aoData ) {
				 /* var x;var param = new Array();
				 for(x in aoData){
					 if(aoData[x].name=='sEcho'||aoData[x].name=='iDisplayStart'||aoData[x].name=='iDisplayLength'){
						param.push(aoData[x]);
					 }
				 } */
			// putQueryData("#${formid!}",aoData);
			// },
			"columns" :[//设定列的所有初始属性
						<#if rows??&&rows?size gt 0>	
							<#list rows as row>
								{
									'data' : <#if row??&&row=='null'>null,"class":'details-control',"defaultContent": ''<#else>'${row!}'</#if>
								},
							</#list>
						</#if>
			            ],
				"columnDefs" : [//设置定义列的初始属性
	            	<#if batch>           
						{
							"render" : function(data, type, row) {
								/* var td = '<td><input type="checkbox" name="${batchId}" class="checkboxes" value='
										+ data + ' /></td>'; */
									var td ='<td><input type="checkbox" name="${batchId}" id="checkbox_'+data+'" class="regular-checkbox" value='
										+ data + ' /><label for="checkbox_'+data+'"></label></td>'
								return td;
							},
							"targets" : 0
						},
					</#if>
					<#if operations??&&operations?size gt 0>
						{
							"render":function(data,type,row){
								var td = '';
								<#list operations as opera>
										<#if opera.showParam??&&opera.showVal??>
											if(row.${opera.showParam}==${opera.showVal}){
												td += '<a href="javascript:;" onclick="<#if opera.js??>${opera.js}(p_${opera.tag},\''+row.${keyId}+'\',this)<#else>_oper(p_${opera.tag},\''+row.${keyId}+'\',this)</#if>"  class="s-oper-btn btn btn-sm ${opera.color!blue}" title="${opera.title!}">${opera.label!}  <i class="fa fa-${opera.icon}"></i></a>';
											}
										<#else>
											td += '<a href="javascript:;" onclick="<#if opera.js??>${opera.js}(p_${opera.tag},\''+row.${keyId}+'\',this)<#else>_oper(p_${opera.tag},\''+row.${keyId}+'\',this)</#if>"  class="s-oper-btn btn btn-sm ${opera.color!blue}" title="${opera.title!}">${opera.label!}  <i class="fa fa-${opera.icon}"></i></a>';
										</#if>
								</#list>
								/* var td ='<a href="#" class="btn btn-sm red">删除 <i class="fa fa-times"></i></a>';
								td +='<a href="#" class="btn btn-sm blue">修改 <i class="fa fa-edit"></i></a>'
								td +='<a href="#" class="btn btn-sm default">查看 <i class="fa fa-info"></i></a>' */
							return td;
							},
							"className":"nowrap",
							"targets":${rows?size}
						},
					</#if>
					<#if formatter?? && formatter?size gt 0>
						<#list formatter as format>
							{
								"render":${format.fun!},
								"targets":${format.tg!}
							},
						</#list>
					</#if>
				 ],
			"language" : {//定义方言
				"zeroRecords":"暂无数据！",
				"processing":"正在加载数据中...",//当table处理用户处理信息时，显示的信息字符串
				"loadingRecords": "正在加载数据...",//加载数据时的提示信息 - 当 Ajax请求数据时显示
				"emptyTable":"暂无数据",//当表格没有数据时，表格所显示的字符串
				"info" : "显示  _START_ 至  _END_ 项结果,共 _TOTAL_ 项",
				"infoEmpty": "显示第 0 至 0 项结果，共 0 项",
				"lengthMenu" : "  每页显示 _MENU_ 项",
				"infoFiltered":"",//当表格搜索后，在汇总字符串上需要增加的内容
				"paginate" : {
					"previous" : "上一页",
					"next" : "下一页",
					"last" : "尾页",
					"first" : "首页"
				}
			},
			"lengthMenu" : [ [ 10, 50, 100, 500],//option value
			                 [ 10,50,100,500]//text
							]//分页数
		});
		//绑定datatable 的绘制完成事件
		table.on( 'draw.dt', function () {
	       // Metronic.initAjax();
			 Metronic.stopPageLoading();
			${drawEvent}
	     } );
		//绑定datatable xhr 请求前事件
		 table.on( 'preXhr.dt', function () {
			 Metronic.startPageLoading();
	     } );
		//绑定datatable xhr 数据错误事件
		 table.on( 'error.dt', function ( e, settings, techNote, message) {
			 console.log("错误data:"+message);
			 Metronic.stopPageLoading();
			 Metronic.alert({
	                message: jsondata.msg,
	                type:"danger"
				})
		 	
	     } );
		 //checkbox 全选 点击
	     table.find('#checkbox-all').change(function () {
	    	 console.log('adsdadasdsada');
	         var set = $(this).attr("data-set");
	         var checked = $(this).is(":checked");
	         $(set).each(function () {
	             if (checked) {
	                 $(this).prop("checked", true);
	             /*  $(this).parents('tr').addClass("selected");  */
	             } else {
	                 $(this).prop("checked", false);
	            /*  $(this).parents('tr').removeClass("selected"); */
	             }
	         });
	         //$.uniform.update(set);
	     });
		 //选中改变背景颜色
	     $('#sample_dt tbody').on( 'click', 'tr', function () {
	         if ( $(this).hasClass('selected') ) {
	             $(this).removeClass('selected');
	         }
	         else {
	             table.$('tr.selected').removeClass('selected');
	             $(this).addClass('selected');
	         }
	     } );
	}
	//重置表单
	$('.reset').on('click',function(){
		$("#${formid!} .query_control input").val('');
		$("#${formid!} .query_control select").val('');
 	});
	//封装操作action的属性成对象 
	<#if operations??&&operations?size gt 0>
		<#list operations as operation>			
			var p_${operation.tag} ={action:"${operation.action}",
				<#if operation.msg??>msg:"${operation.msg}",</#if>
				remote:${operation.remote?c}
				};
		</#list>
		/* 单个操作 */
		function _oper(option,id){
			var data = {${keyId}:id};
			var url = option.action;
			if(option.remote){
				if(option.msg){
					confirmModal('show',option.msg);
					$('#confirm-modal .dosure').unbind('click').on('click',function(e){
						getRemote(url,data);
					});
				}else{
					getRemote(url,data);
				}
			}else{
				if(option.msg){
					confirmModal('show',option.msg);
					$('#confirm-modal .dosure').unbind('click').on('click',function(e){
						postData(url,data);
					});
				}else{
					postData(url,data);
				}
			}
		}
	</#if>
	<#if batchAction??&&batchAction?size gt 0>
		<#list batchAction as action>			
			var b_${action.tag} ={action:"${action.action}",
				<#if action.msg??>msg:"${action.msg}",</#if>
				remote:${action.remote?c},select:<#if action.select??>${action.select?c}<#else>false</#if>
				};
		</#list>
		/*批量操作 */
		function _batchop(option){
			var url = option.action;
			var datas=new Array();
			if(option.select){
				putQueryData("input[name=${batchId}]",datas);
				if(datas.length==0){
					Metronic.alert({
		                message: "请选择要操作的数据！",
		                type:"danger"
					});
					return;
				}
			}
			if(option.remote){
				/* if(option.select){
					$.each(datas,function(i,data){
						url+="?"+data.name+"="+data.value;
					})
				} */
				if(option.msg){
					confirmModal('show',option.msg);
					$('#confirm-modal .dosure').unbind('click').on('click',function(e){
						getRemote(url,datas);
					});
				}else{
					getRemote(url,datas);
				}
			}else{
				if(option.msg){
					confirmModal('show',option.msg);
					$('#confirm-modal .dosure').unbind('click').on('click',function(e){
						postData(url,datas);
					});
				}else{
					postData(url,datas);
				}
			}
		}
	</#if>
	function reload(){
		table.api().ajax.reload();//_fnAjaxUpdate();
		//table.ajax.reload();
	}
	function postData(url,data){
		console.log("t post");
		ajaxData(url,data,cb);
	}
	var cb = function(jsondata){
		jsondata = $.parseJSON(jsondata);
		if(jsondata.success){
			Metronic.alert({
                message: jsondata.msg,
                type:"success"
			})
			table._fnAjaxUpdate(); 
		}else{
			Metronic.alert({
                message: jsondata.msg,
                type:"danger"
			})
		}
	}
	function docallback(data){
		alert(data);
		if(data.success){
			Metronic.alert({
                message: data.msg,
                type:"success"
			})
			table._fnAjaxUpdate(); 
		}else{
			Metronic.alert({
                message: data.msg,
                type:"danger"
			})
		}
	}
</script>
</#macro> 